#include "Server.hpp"
#include <memory>
#include "daemon.hpp"
using namespace my_ser;

static void usage(const char* port)
{
    std::cout<<"USAGE:\n\t"<<port<<" serverip\n"<<std::endl;
}

Response TaskFunc(const Request& req)
{
    Response resp;
    switch(req._op)
    {
        case '+':
            resp._result = req._x + req._y;
            resp._code = 0;
            break;
        case '-':
            resp._result = req._x - req._y;
            resp._code = 0;
            break;
        case '*':
            resp._result = req._x * req._y;
            resp._code = 0;
            break;
        case '/':
            if(req._y == 0) 
            {
                resp._result = 0;
                resp._code = 1;
            }
            else
            {
                resp._result = req._x / req._y;
                resp._code = 0;
            }
            break;
        case '%':
            if(req._y == 0) 
            {
                resp._result = 0;
                resp._code = 2;
            }
            else 
            {
                resp._result = req._x % req._y;
                resp._code = 0;
            }
            break;

        default :
            resp._code = 3;
            break;
    }
    return resp;
}

int main(int argc,char* argv[])
{
    uint16_t port = 8088;
    if(argc == 2)
    {
        port = htons(atoi(argv[1]));
    }
    else if(argc > 2)
    {
        usage(argv[0]);
        exit(USAGE_ERR);
    }

    //daemon(); //守护进程化

    std::unique_ptr<Server> ser(new Server(TaskFunc,port));
    ser->InitServer();
    ser->Start();

    return 0;
}